import type { ReactNode } from 'react'
import { useState } from 'react'

// * p i motion
import { useAnimate } from 'motion/react'

// * p i react-gesture-responder
import { useGestureResponder } from 'react-gesture-responder'

const BOXWIDTH = 128
const NEXTNUMBER = 20

const App = (): ReactNode => {
	const scopeX = useRef(0)
	const offsetX = useRef(0)
	const [index, setIndex] = useState(0)

	const [scope, animate] = useAnimate()

	const setX = (x: number, isDuration = false) => {
		scopeX.current = x
		animate(scope.current, { x }, { duration: isDuration ? 0.2 : 0 })
	}

	const { bind } = useGestureResponder({
		onStartShouldSet: () => true,
		onMove: ({ delta }) => {
			const x = delta[0]
			setX(x + offsetX.current)
		},
		onRelease: ({ delta }) => {
			const x = scopeX.current

			if (x > 0) {
				setX(0, true)
				setIndex(0)
				offsetX.current = 0
				return
			}
			const maxX = -(BOXWIDTH * 2)
			if (x < maxX) {
				setX(maxX, true)
				setIndex(2)
				offsetX.current = maxX
				return
			}
			if (Math.abs(delta[0]) > NEXTNUMBER) {
				const direction: string = delta[0] > 0 ? 'left' : 'right'

				const nextIndex = direction === 'left' ? index - 1 : index + 1
				setIndex(nextIndex)

				const newX = nextIndex * -BOXWIDTH
				setX(newX, true)
				offsetX.current = newX
				return
			}

			const newX = index * -BOXWIDTH
			offsetX.current = newX
			setX(newX, true)
		},
	})
	return (
		<div className="h-screen">
			<div
				className="absolute bottom-8 left-1/2 h-12 w-32 -translate-x-1/2 overflow-hidden ring-2"
				{...bind}
			>
				<div
					ref={scope}
					className="grid h-full w-full grid-cols-[100%_100%_100%]"
				>
					<div className="w-full bg-slate-500"></div>
					<div className="w-full bg-gray-900"></div>
					<div className="w-full bg-neutral-200"></div>
				</div>
			</div>
		</div>
	)
}

export default App
